module test(
	input 		clk,
	input 		rst,

);
	localparam	IDLE	=	4'd0;
	localparam	MAIN	=	4'd1;
	localparam	MODE1	=	4'd2;
	localparam	DELAY	=	4'd8;
	
	reg [3:0] cnt, cnt_main,cnt_mode1,cnt_mode2;
	reg [23:0] cnt_delay, num_delay;
	reg [3:0]  state, state_back;
	
	always(posedge	clk or  negedge rst) begin
		if(!rst) begin	//如果按键复位，将相关数据初始化
			clock_set<=1'b0;init_m<=0;init_h<=0;
			alarm_h<=1;alarm_m<=1;alarm_s<=1;	
			cnt <= 1'b0;
			cnt_main <= 4'd0; cnt_mode1 <= 1'b0; cnt_mode2 <= 1'b0;
			cnt_delay <= 1'b0; num_delay <= 24'd4800;
			state <= IDLE; state_back <= IDLE;
		end
		else begin
			case(state)
				IDLE:begin	//软件自复位，主要用于程序跑飞后的处理
					clock_set<=1'b0;init_m<=0;init_h<=0;
					alarm_h<=1;alarm_m<=0;alarm_s<=0;
					cnt <= 1'b0;
					cnt_main <= 4'd0; cnt_mode1 <= 1'b0; cnt_mode2 <= 1'b0;
					cnt_delay <= 1'b0; num_delay <= 24'd4800;
					state <= IDLE;state_back <= IDLE;
					end
				MAIN:begin
						if(cnt_main>=0)	cnt_main<=0;
						else			cnt_main<=cnt_main+1;	
						case(cnt_main)
							4'd0:begin state <= MODE1;state_back <= state; end	//写入当前时间
							4'd1:begin ; end	//卡死
							default: state <= IDLE;	//如果程序失控，进入IDLE自复位状态
						endcase
					end
				MODE1:begin	//写入任务，
						if(cnt_mode1>=8)cnt_mode1<=0;
						else			cnt_mode1<=cnt_mode1+1;	
						case(cnt_mode1)
							4'd0:begin reg_addr<=8'b0000_0001;w_r<=1;data_in<=time_s;end	//写入秒
							4'd1:begin state <= DELAY;num_delay <= 24'd4800;state_back <= state; end	//延时
							4'd2:begin state <= DELAY;num_delay <= 24'd4800;state_back <= state;w_r<=0; end	//延时
							4'd3:begin reg_addr<=8'b0000_0010;w_r<=1;data_in<=time_m;end	//写入分
							4'd4:begin state <= DELAY;num_delay <= 24'd4800;state_back <= state; end	//延时
							4'd5:begin state <= DELAY;num_delay <= 24'd4800;state_back <= state;w_r<=0; end	//延时
							4'd6:begin reg_addr<=8'b0000_0010;w_r<=1;data_in<=time_h;end	//写入时
							4'd7:begin state <= DELAY;num_delay <= 24'd4800;state_back <= state; end	//延时
							4'd8:begin state <= DELAY;num_delay <= 24'd4800;state_back <= state;w_r<=0; end	//延时
							default: state <= IDLE;	//如果程序失控，进入IDLE自复位状态
						endcase
					end
				DELAY:begin	//延时任务
						if(cnt_delay >= num_delay) begin
							cnt_delay <= 1'b0;
							state <= state_back; //返回原程序
						end else cnt_delay <= cnt_delay + 1'b1;
					end
				default:state <= IDLE;//如果程序失控，进入IDLE自复位状态
			endcase
		
		end
	end


endmodule


